/**
 * ETF网格交易1.0系统 - 压力测试核心逻辑
 * 遵循DRY、KISS、SOLID、YAGNI原则
 */

class GridTradingSystem {
    constructor() {
        this.gridData = [];
        this.priceHistory = [];
        this.profitHistory = [];
        this.charts = {};
        this.initializeCharts();
    }

    /**
     * 初始化图表
     */
    initializeCharts() {
        // 价格走势图
        const priceCtx = document.getElementById('priceChart').getContext('2d');
        this.charts.price = new Chart(priceCtx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: '价格走势',
                    data: [],
                    borderColor: '#667eea',
                    backgroundColor: 'rgba(102, 126, 234, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: '价格走势与网格交易点'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: false,
                        title: {
                            display: true,
                            text: '价格'
                        }
                    }
                }
            }
        });

        // 收益曲线图
        const profitCtx = document.getElementById('profitChart').getContext('2d');
        this.charts.profit = new Chart(profitCtx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: '累计收益',
                    data: [],
                    borderColor: '#27ae60',
                    backgroundColor: 'rgba(39, 174, 96, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: '累计收益曲线'
                    }
                },
                scales: {
                    y: {
                        title: {
                            display: true,
                            text: '收益 (元)'
                        }
                    }
                }
            }
        });
    }

    /**
     * 生成网格数据
     */
    generateGridData(params) {
        const { initialPrice, gridMode, gridSize, gridStep, totalAmount, gridCount } = params;
        const gridData = [];
        const amountPerGrid = totalAmount / gridCount;

        for (let i = 0; i < gridCount; i++) {
            let buyPrice, sellPrice;
            
            if (gridMode === 'percentage') {
                // 百分比模式：等比数列
                buyPrice = initialPrice * Math.pow(1 - gridSize / 100, i);
                sellPrice = i === 0 ? initialPrice * (1 + gridSize / 100) : 
                           initialPrice * Math.pow(1 - gridSize / 100, i - 1);
            } else {
                // 固定步长模式：等差数列
                buyPrice = initialPrice - (gridStep * i);
                sellPrice = i === 0 ? initialPrice + gridStep : 
                           initialPrice - (gridStep * (i - 1));
            }

            const expectedReturn = (sellPrice - buyPrice) * (amountPerGrid / buyPrice);
            const returnRate = (sellPrice - buyPrice) / buyPrice * 100;

            gridData.push({
                level: i + 1,
                buyPrice: buyPrice.toFixed(4),
                sellPrice: sellPrice.toFixed(4),
                amount: amountPerGrid.toFixed(2),
                expectedReturn: expectedReturn.toFixed(2),
                returnRate: returnRate.toFixed(2)
            });
        }

        return gridData;
    }

    /**
     * 模拟价格波动
     */
    simulatePriceMovement(initialPrice, maxDecline, gridCount, gridParams) {
        const priceHistory = [initialPrice];
        const profitHistory = [0];
        const gridData = this.generateGridData({
            initialPrice,
            ...gridParams,
            totalAmount: 100000,
            gridCount
        });

        let currentPrice = initialPrice;
        let totalProfit = 0;
        let completedTrades = 0;

        // 模拟价格下跌到最大跌幅
        const minPrice = initialPrice * (1 - maxDecline / 100);
        const steps = 100;
        
        for (let i = 1; i <= steps; i++) {
            // 模拟价格波动（加入随机性）
            const declineProgress = i / steps;
            const basePrice = initialPrice * (1 - maxDecline / 100 * declineProgress);
            const randomFactor = 0.95 + Math.random() * 0.1; // ±5%随机波动
            currentPrice = basePrice * randomFactor;

            priceHistory.push(currentPrice);

            // 检查网格交易触发
            const newTrades = this.checkGridTriggers(currentPrice, gridData, completedTrades);
            totalProfit += newTrades.profit;
            completedTrades += newTrades.count;

            profitHistory.push(totalProfit);
        }

        return { priceHistory, profitHistory, completedTrades, totalProfit };
    }

    /**
     * 检查网格交易触发
     */
    checkGridTriggers(currentPrice, gridData, completedTrades) {
        let profit = 0;
        let count = 0;

        for (let i = completedTrades; i < gridData.length; i++) {
            const grid = gridData[i];
            const buyPrice = parseFloat(grid.buyPrice);
            const sellPrice = parseFloat(grid.sellPrice);

            // 检查是否触发买入
            if (currentPrice <= buyPrice) {
                // 模拟买入后价格上涨到卖出点
                const tradeProfit = parseFloat(grid.expectedReturn);
                profit += tradeProfit;
                count++;
            }
        }

        return { profit, count };
    }

    /**
     * 计算统计指标
     */
    calculateStatistics(gridData, simulationResult) {
        const { totalProfit, completedTrades } = simulationResult;
        const totalAmount = 100000; // 总投入
        const totalReturnRate = (totalProfit / totalAmount) * 100;
        const avgReturnPerTrade = completedTrades > 0 ? totalProfit / completedTrades : 0;
        const maxDrawdown = this.calculateMaxDrawdown(simulationResult.profitHistory);

        return {
            totalProfit: totalProfit.toFixed(2),
            totalReturnRate: totalReturnRate.toFixed(2),
            completedTrades,
            avgReturnPerTrade: avgReturnPerTrade.toFixed(2),
            maxDrawdown: maxDrawdown.toFixed(2),
            totalAmount: totalAmount.toFixed(2)
        };
    }

    /**
     * 计算最大回撤
     */
    calculateMaxDrawdown(profitHistory) {
        let maxDrawdown = 0;
        let peak = 0;

        for (const profit of profitHistory) {
            if (profit > peak) {
                peak = profit;
            }
            const drawdown = peak - profit;
            if (drawdown > maxDrawdown) {
                maxDrawdown = drawdown;
            }
        }

        return maxDrawdown;
    }

    /**
     * 更新统计卡片
     */
    updateStatsGrid(stats) {
        const statsGrid = document.getElementById('statsGrid');
        statsGrid.innerHTML = `
            <div class="stat-card">
                <h3>总收益</h3>
                <div class="value ${stats.totalProfit >= 0 ? 'profit' : 'loss'}">
                    ¥${stats.totalProfit}
                </div>
            </div>
            <div class="stat-card">
                <h3>总收益率</h3>
                <div class="value ${stats.totalReturnRate >= 0 ? 'profit' : 'loss'}">
                    ${stats.totalReturnRate}%
                </div>
            </div>
            <div class="stat-card">
                <h3>完成交易数</h3>
                <div class="value">${stats.completedTrades}</div>
            </div>
            <div class="stat-card">
                <h3>平均每笔收益</h3>
                <div class="value ${stats.avgReturnPerTrade >= 0 ? 'profit' : 'loss'}">
                    ¥${stats.avgReturnPerTrade}
                </div>
            </div>
            <div class="stat-card">
                <h3>最大回撤</h3>
                <div class="value loss">¥${stats.maxDrawdown}</div>
            </div>
            <div class="stat-card">
                <h3>总投入</h3>
                <div class="value">¥${stats.totalAmount}</div>
            </div>
        `;
    }

    /**
     * 更新网格表格
     */
    updateGridTable(gridData) {
        const tbody = document.getElementById('gridTableBody');
        tbody.innerHTML = gridData.map(grid => `
            <tr>
                <td>${grid.level}</td>
                <td>${grid.buyPrice}</td>
                <td>${grid.sellPrice}</td>
                <td>¥${grid.amount}</td>
                <td class="${parseFloat(grid.expectedReturn) >= 0 ? 'profit' : 'loss'}">
                    ¥${grid.expectedReturn}
                </td>
                <td class="${parseFloat(grid.returnRate) >= 0 ? 'profit' : 'loss'}">
                    ${grid.returnRate}%
                </td>
            </tr>
        `).join('');
    }

    /**
     * 更新图表
     */
    updateCharts(simulationResult) {
        const { priceHistory, profitHistory } = simulationResult;
        const labels = priceHistory.map((_, index) => `第${index + 1}天`);

        // 更新价格图表
        this.charts.price.data.labels = labels;
        this.charts.price.data.datasets[0].data = priceHistory;
        this.charts.price.update();

        // 更新收益图表
        this.charts.profit.data.labels = labels;
        this.charts.profit.data.datasets[0].data = profitHistory;
        this.charts.profit.update();
    }

    /**
     * 运行压力测试
     */
    runStressTest() {
        const gridMode = document.getElementById('gridMode').value;
        const params = {
            etfName: document.getElementById('etfName').value,
            initialPrice: parseFloat(document.getElementById('initialPrice').value),
            gridMode: gridMode,
            gridSize: parseFloat(document.getElementById('gridSize').value),
            gridStep: parseFloat(document.getElementById('gridStep').value),
            totalAmount: parseFloat(document.getElementById('totalAmount').value),
            maxDecline: parseFloat(document.getElementById('maxDecline').value),
            gridCount: parseInt(document.getElementById('gridCount').value)
        };

        // 生成网格数据
        const gridData = this.generateGridData(params);
        this.updateGridTable(gridData);

        // 准备网格参数
        const gridParams = {
            gridMode: params.gridMode,
            gridSize: params.gridSize,
            gridStep: params.gridStep
        };

        // 运行模拟
        const simulationResult = this.simulatePriceMovement(
            params.initialPrice,
            params.maxDecline,
            params.gridCount,
            gridParams
        );

        // 计算统计指标
        const stats = this.calculateStatistics(gridData, simulationResult);
        this.updateStatsGrid(stats);

        // 更新图表
        this.updateCharts(simulationResult);

        // 显示结果摘要
        this.showResultSummary(params, stats);
    }

    /**
     * 显示结果摘要
     */
    showResultSummary(params, stats) {
        const gridModeText = params.gridMode === 'percentage' ? 
            `百分比模式 (${params.gridSize}%)` : 
            `固定步长模式 (${params.gridStep}元)`;
            
        const summary = `
压力测试完成！

ETF品种: ${params.etfName}
初始价格: ${params.initialPrice}
网格模式: ${gridModeText}
最大下跌: ${params.maxDecline}%
网格层数: ${params.gridCount}

测试结果:
- 总收益: ¥${stats.totalProfit}
- 总收益率: ${stats.totalReturnRate}%
- 完成交易: ${stats.completedTrades}笔
- 最大回撤: ¥${stats.maxDrawdown}
        `;

        alert(summary);
    }
}

// 全局实例
const gridSystem = new GridTradingSystem();

// 运行压力测试函数
function runStressTest() {
    gridSystem.runStressTest();
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 可以在这里添加初始化逻辑
    console.log('ETF网格交易1.0系统已加载');
});